<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="searchFormRef" :model="queryParam" :inline="true">
        <el-form-item label="名称" prop="keywords">
          <el-input v-model="queryParam.keywords" placeholder="权限名称关键字" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery"> <i-ep-refresh />重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button v-hasPerm="['permission:add']" type="success"
          @click="handleOpenAddDialog()"><i-ep-plus />新增</el-button>
        <el-button v-hasPerm="['permission:del']" type="danger" @click="handleDelete()"><i-ep-delete />删除
        </el-button>
      </template>

      <el-table v-loading="loading" :data="permissionData" row-key="id" lazy :load="loadTreeData"
        :tree-props="{ children: 'children', hasChildren: 'children' }">
        <el-table-column prop="name" label="名称" min-width="200" />
        <el-table-column prop="alias" label="别名" width="200" />
        <el-table-column prop="service_id" label="微服务ID" width="150" />
        <el-table-column prop="api_pattern" label="路径模式" width="150" />
        <el-table-column prop="api_method" label="请求方法" width="150" />
        <el-table-column prop="api_bypass" label="授权方式" width="150" />
        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button v-hasPerm="['permission:add']" type="primary" link size="small"
              @click.stop="handleOpenAddDialog(scope.row)"><i-ep-plus />新增
            </el-button>
            <el-button v-hasPerm="['permission:edit']" type="primary" link size="small"
              @click.stop="handleOpenEditDialog(scope.row)"><i-ep-edit />编辑
            </el-button>
            <el-button v-hasPerm="['permission:del']" type="danger" link size="small"
              @click.stop="handleDelete(scope.row.id)">
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination v-if="pagination.total > 0" v-model:total="pagination.total" v-model:page="pagination.current"
        v-model:limit="pagination.size" @pagination="handlePageChange" />
    </el-card>
    <!--表单数据-->
    <Form ref="permissionFormRef" v-model="dialog.visible" :title="dialog.title" :permission-item="selectedItem"
      @close="handleCloseDialog" @submit="handleDialogSubmit" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Permission",
  inheritAttrs: false,
})

import PermissionAPI, { PermissionVO, PermissionQuery } from "@/api/permission"
import { buildTree } from "@/utils";
import Form from "./form.vue";

const searchFormRef = ref(ElForm)

const loading = ref(false)
const dialog = reactive({
  title: "新增",
  visible: false,
})


const selectedItem = ref<PermissionVO>()

const queryParam = reactive<PermissionQuery>({})

const permissionData = ref<PermissionVO[]>()

const queryCondition = reactive<QueryCondition>({})


const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})



const getPermissionTree = () => {
  loading.value = true
  PermissionAPI.queryPage(queryCondition).then((res) => {
    if (res.status == 200) {
      res.data.records.forEach((item: PermissionVO) => {
        item.children = []
      })
      permissionData.value = buildTree(res.data.records, "id", "pid", "id", "name")
      pagination.total = res.data.total
    }
  }).finally(() => { loading.value = false })
}

const loadTreeData = (row: PermissionVO, treeNode: unknown, resolve: (data: PermissionVO[]) => void) => {
  queryCondition.and = []
  queryCondition.paging = { current: 1, size: 9999 }
  queryCondition.and?.push({ field: 'pid', op: '=', value: row.id })
  PermissionAPI.query(queryCondition).then((res) => {
    if (res.status == 200) {
      resolve(res.data)
    }
  }).finally(() => { loading.value = false })
}

const handlePageChange = () => {
  queryCondition.paging = { ...pagination }
  handleQuery()
}

const handleInitPage = () => {
  queryCondition.and = [{ field: 'pid', op: '=', value: 0 }]
  queryCondition.paging = { current: pagination.current, size: pagination.size }
  getPermissionTree()
}

/** 查询权限 */
const handleQuery = () => {
  queryCondition.and = [{ field: 'pid', op: '=', value: 0 }]
  if (queryParam.keywords) {
    queryCondition.and?.push({ field: 'name', op: 'like', value: `%${queryParam.keywords}%` })
  }
  queryCondition.paging = Object.assign({}, pagination)

  getPermissionTree()
}

/** 重置查询 */
const handleResetQuery = () => {
  if (searchFormRef.value) {
    searchFormRef.value.resetFields()
  }
  handleQuery()
}


/**
 * 打开新增权限弹窗
 *
 */
const handleOpenAddDialog = (row: PermissionVO = {}) => {
  dialog.title = "新增权限"
  if (row.id) {
    selectedItem.value = {
      pid: row.id
    }
  }
  dialog.visible = true
}
/**
 * 打开编辑权限弹窗
 */
const handleOpenEditDialog = (row: PermissionVO = {}) => {
  dialog.title = "修改权限"
  selectedItem.value = Object.assign({}, row)
  dialog.visible = true
}


// 删除菜单
const handleDelete = (permissionId?: number) => {
  if (!permissionId) {
    ElMessage.warning("请勾选删除项")
    return
  }
  ElMessageBox.confirm("确认删除已选中的权限及其子权限么?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    const deleteCondition: QueryCondition = {
      "_cond": { and: [{ field: "id", op: "in", value: [permissionId] }] }
    }
    PermissionAPI.deleteBy(deleteCondition).then((res) => {
      if (res.status === 200) {
        ElMessage.success("删除成功")
        handleQuery()
      }
    }).finally(() => {
      loading.value = false
    })
  })
}

/** 提交权限表单 */
const handleDialogSubmit = () => {
  dialog.visible = false
  handleInitPage()
}

/** 关闭弹窗 */
const handleCloseDialog = () => {
  dialog.visible = false
}

onMounted(() => {
  handleInitPage()
})
</script>
